<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="LeMemberInfoForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="宝贝名字" v-bind="validateInfos.bbName" id="LeMemberInfoForm-bbName" name="bbName">
                <a-input v-model:value="formData.bbName" placeholder="请输入宝贝名字" allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="宝贝年龄" id="LeMemberInfoForm-ageInMonths" name="ageInMonths">
                <a-input v-model:value="ageInMonths" placeholder="宝贝年龄根据出生日期自动计算" disabled allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="宝贝性别" v-bind="validateInfos.sex" id="LeMemberInfoForm-sex" name="sex">
                <j-dict-select-tag type='radio' v-model:value="formData.sex" dictCode="sex" placeholder="请选择宝贝性别" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="出生日期" v-bind="validateInfos.birthDate" id="LeMemberInfoForm-birthDate" name="birthDate">
                <a-date-picker placeholder="请选择出生日期" v-model:value="formData.birthDate" value-format="YYYY-MM-DD" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="联系电话" v-bind="validateInfos.phone" id="LeMemberInfoForm-phone" name="phone">
                <a-input v-model:value="formData.phone" placeholder="请输入联系电话" allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="家庭住址" v-bind="validateInfos.address" id="LeMemberInfoForm-address" name="address">
                <a-input v-model:value="formData.address" placeholder="请输入家庭住址" allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注" v-bind="validateInfos.remark" id="LeMemberInfoForm-remark" name="remark">
                <a-textarea v-model:value="formData.remark" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../LeMemberInfo.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });

  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  
  const formData = reactive<Record<string, any>>({
    id: '',
    bbName: '',
    sex: undefined,
    birthDate: '',
    phone: '',
    address: '',
    remark: '',
  });

  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);

  const validatorRules = reactive({
    bbName: [{ required: true, message: '请输入宝贝名字!' }],
    sex: [{ required: true, message: '请输入宝贝性别!' }],
    birthDate: [
    { required: true, message: '请输入出生日期!' },
    {
      validator: (_, value) => {
        const today = new Date();
        const selectedDate = new Date(value);
        if (selectedDate > today) {
          return Promise.reject(new Error('出生日期不能大于今天!'));
        }
        return Promise.resolve();
      },
    },
  ],
    phone: [{ required: false }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!' }],
  });

  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  const disabled = computed(() => {
    if (props.formBpm === true) {
      return props.formData.disabled === true || props.formDisabled;
    }
    return props.formDisabled;
  });

  // 计算年龄（几岁几月几天）
  const ageInMonths = computed(() => {

  if (!formData.birthDate) return ''; // 没有出生日期时返回空
  const birthDate = new Date(formData.birthDate);
  const today = new Date();

  if (isNaN(birthDate.getTime())) {
    return ''; // 如果出生日期无效，则返回空
  }    
    // 计算年份差
    let years = today.getFullYear() - birthDate.getFullYear();
    // 计算月份差
    let months = today.getMonth() - birthDate.getMonth();
    // 计算天数差
    let days = today.getDate() - birthDate.getDate();

      // 如果出生日期是今天
    if (birthDate.toDateString() === today.toDateString()) {
      return '0天'; // 返回默认值0天
    }
    
    // 处理天数差
    if (days < 0) {
      months--;
      days += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
    }
    
    // 处理月份差
    if (months < 0) {
      years--;
      months += 12;
    }
    
    // 构建年龄字符串
    let stringMonths = '';
    if (years > 0) {
      stringMonths += years + '岁';
    }
    if (months > 0) {
      stringMonths += months + '月';
    }
    if (days > 0) {
      stringMonths += days + '天';
    }
     
    // 更新 formData 中的 ageInMonths 字段
    formData.ageInMonths = stringMonths.trim();
  
    return stringMonths.trim(); // 返回构建的字符串
  });

  // 监听出生日期的变化，自动更新年龄
  watch(() => formData.birthDate, () => {
    // 此处可进行其他操作
    
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      // 赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    // 时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    // 循环数据
    for (let data in model) {
      // 如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        // 如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
